﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Linq;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using System.IO;

namespace PRO_DOCS.DocumentManagementSystem.ADMIN.WIN.Configurations.Maps
{
    public partial class MapsCategoriesSettings : BLL.WIN.Templates.DevxConfigurationUserControlTemplate
    {
        bool IMAGE_CHANGED { get; set; }
        string SELECTED_IMAGE_PATH
        { get; set; }
        DAL.Database.MapCategory CURRENT_SELECTED_MAP_CATEGORY
        {
            get;
            set;
        }

        List<DAL.Database.MapCategory> MAP_CATEGORIES
        {
            get;
            set;
        }
        Dictionary<int, int> ARCHIVE_DEPARTMENTS_STORAGES_HEIRARCHIES
        { get; set; }
        public MapsCategoriesSettings()
        {
            InitializeComponent();

            //System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MapsCategoriesSettings));
            //this.picCategoryIcon.EditValue = ((object)(resources.GetObject("picCategoryIcon.EditValue")));
            this.picCategoryIcon.Image = Image.FromFile(@"Resources\country_32x32.png");


            btnAddNew.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(btnAddNew_ItemClick);
            btnDeleteItem.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(btnDeleteItem_ItemClick);
            btnSaveUpdate.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(btnSaveUpdate_ItemClick);
            btnRefresh.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(btnRefresh_ItemClick);

            //Load storage medias
            ARCHIVE_DEPARTMENTS_STORAGES_HEIRARCHIES = new Dictionary<int, int>();
            comboDepartmentStorageMedia.Properties.Items.BeginUpdate();
            comboDepartmentStorageMedia.Properties.Items.Clear();
            int i = 0;
            PRO_DOCSDatabaseDataContext.proc_ARCHIVE_DEPARTMENTS_STORAGES_HEIRARCHIESLoadAll().ToList().ForEach(new Action<PRO_DOCS.DAL.Database.proc_ARCHIVE_DEPARTMENTS_STORAGES_HEIRARCHIESLoadAllResult>(delegate(PRO_DOCS.DAL.Database.proc_ARCHIVE_DEPARTMENTS_STORAGES_HEIRARCHIESLoadAllResult _sTORAGE_HEIRARCHY)
            {
                ARCHIVE_DEPARTMENTS_STORAGES_HEIRARCHIES.Add(i, _sTORAGE_HEIRARCHY.ARCHIVE_DEPARTMENT_STORAGE_HEIRARCHY_ID);
                comboDepartmentStorageMedia.Properties.Items.Add(_sTORAGE_HEIRARCHY.ARCHIVE_DEPARTMENT_STORAGE_HEIRARCHY_NAME);
                i++;
            }));

            comboDepartmentStorageMedia.Properties.Items.EndUpdate();
            comboDepartmentStorageMedia.SelectedIndex = -1;

            RELOAD_ALL_MAP_CATEGORIES();
        }

        void btnAddNew_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            CLEAR_MAP_REGION();
        }

        void btnRefresh_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            RELOAD_ALL_MAP_CATEGORIES();
        }

        private void RELOAD_ALL_MAP_CATEGORIES()
        {
            MAP_CATEGORIES = PRO_DOCSDatabaseDataContext.MapCategories.ToList();
            gridControl1.DataSource = MAP_CATEGORIES;
        }

        void btnSaveUpdate_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            dxErrorProvider1.ClearErrors();

            bool continue_data_saving = !string.IsNullOrEmpty(txtCategoryName.Text) && comboDepartmentStorageMedia.SelectedIndex > -1;

            if (continue_data_saving)
            {

                int? new_map_category_id = 0;
                bool file_uploaded = false;
                string new_file_name = Guid.NewGuid().ToString();
                if (IMAGE_CHANGED)
                {
                    FileInfo fiImage = new FileInfo(SELECTED_IMAGE_PATH);

                    List<string> file_pathes = (from pathes in PRO_DOCSDatabaseDataContext.ARCHIVE_DEPARTMENTS_STORAGES_HEIRARCHY_PHYSICAL_PATHEs
                                                where pathes.ARCHIVE_DEPARTMENT_STORAGE_HEIRARCHY_ID.Value.Equals(ARCHIVE_DEPARTMENTS_STORAGES_HEIRARCHIES[comboDepartmentStorageMedia.SelectedIndex])
                                                select pathes.ARCHIVE_DEPARTMENTS_STORAGES_HEIRARCHY_PHYSICAL_PATH).ToList();

                    for (int i = 0; i < file_pathes.Count; i++)
                    {
                        try
                        {
                            new PRO_DOCS.BLL.WIN.Utilities.ImagesManager().ScaleImage(Image.FromFile(fiImage.FullName), 32, 32).Save(Path.Combine(file_pathes[i], new_file_name + fiImage.Extension));

                            new_file_name = new_file_name + fiImage.Extension;

                            file_uploaded = true;

                            break;
                        }
                        catch { }
                    }
                }
                if (CURRENT_SELECTED_MAP_CATEGORY.MapCategoryID.Equals(0))
                {

                    if (file_uploaded)
                    {

                        PRO_DOCSDatabaseDataContext.proc_MapCategoriesInsert
                            (
                            ref new_map_category_id,
                            txtCategoryName.Text,
                            new_file_name,
                            ARCHIVE_DEPARTMENTS_STORAGES_HEIRARCHIES[comboDepartmentStorageMedia.SelectedIndex],
                            !chkIsActive.Checked);
                        RELOAD_ALL_MAP_CATEGORIES();
                    }
                    else
                    {
                        dxErrorProvider1.SetError(picCategoryIcon, BLL.WIN.Properties.ErrorProviderMessages.Default.InputLeftBlank.Replace("{name}", "Category image"));
                    }

                }
                else
                {
                    new_map_category_id = CURRENT_SELECTED_MAP_CATEGORY.MapCategoryID;

                    new_file_name = (IMAGE_CHANGED) ? new_file_name : CURRENT_SELECTED_MAP_CATEGORY.MapCategoryIcon;
                    PRO_DOCSDatabaseDataContext.proc_MapCategoriesUpdate
                        (new_map_category_id,
                        txtCategoryName.Text,
                        new_file_name,
                        ARCHIVE_DEPARTMENTS_STORAGES_HEIRARCHIES[comboDepartmentStorageMedia.SelectedIndex],
                        !chkIsActive.Checked);


                    gridView1.SetRowCellValue(gridView1.FocusedRowHandle, gcCategoryName, txtCategoryName.Text);
                    gridView1.SetRowCellValue(gridView1.FocusedRowHandle, gcStorageHeirarchy, comboDepartmentStorageMedia.Text);
                    gridView1.SetRowCellValue(gridView1.FocusedRowHandle, gcIsDeleted, !chkIsActive.Checked);
                }
                IMAGE_CHANGED = false;
                CURRENT_SELECTED_MAP_CATEGORY = (from categ in PRO_DOCSDatabaseDataContext.MapCategories
                                                 where categ.MapCategoryID.Equals(new_map_category_id.Value)
                                                 select categ).FirstOrDefault();
            }
            else
            {
                if (string.IsNullOrEmpty(txtCategoryName.Text))
                {
                    dxErrorProvider1.SetError(txtCategoryName, BLL.WIN.Properties.ErrorProviderMessages.Default.InputLeftBlank.Replace("{name}", "Category name"));
                }

                if (comboDepartmentStorageMedia.SelectedIndex.Equals(-1))
                {

                    dxErrorProvider1.SetError(comboDepartmentStorageMedia, BLL.WIN.Properties.ErrorProviderMessages.Default.InputLeftBlank.Replace("{name}", "saving path"));
                }
            }
        }

        void btnDeleteItem_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (XtraMessageBox.Show("Deleting this Map Category will lead to removing all it's related regions.\nAre you sure you want to delete this Category?", BLL.WIN.Properties.Messages.Default.DeleteCaption, MessageBoxButtons.OKCancel, MessageBoxIcon.Question).Equals(DialogResult.OK))
            {
                PRO_DOCSDatabaseDataContext.proc_MapCategoriesDelete(CURRENT_SELECTED_MAP_CATEGORY.MapCategoryID);

                gridView1.DeleteSelectedRows();
            }
        }

        private void CLEAR_MAP_REGION()
        {
            IMAGE_CHANGED = false;
            SELECTED_IMAGE_PATH = string.Empty;

            txtCategoryName.Text = string.Empty;
            this.picCategoryIcon.Image = Image.FromFile(@"Resources\country_32x32.png");
            comboDepartmentStorageMedia.SelectedIndex = -1;
            chkIsActive.Checked = true;

            CURRENT_SELECTED_MAP_CATEGORY = new DAL.Database.MapCategory();
        }

        private void picCategoryIcon_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Title = "Select the Map Image file.";
            ofd.Filter = ofd.Filter = "Image file|*.png; *.jpg; *.jpeg; *.bmp; *.gif";

            if (ofd.ShowDialog().Equals(DialogResult.OK))
            {
                IMAGE_CHANGED = true;
                SELECTED_IMAGE_PATH = ofd.FileName;
                picCategoryIcon.Image = Image.FromFile(ofd.FileName);

            }
        }

        private void gridView1_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            CLEAR_MAP_REGION();

            if (e.FocusedRowHandle > -1)
            {
                CURRENT_SELECTED_MAP_CATEGORY = gridView1.GetFocusedRow() as DAL.Database.MapCategory;
                CURRENT_SELECTED_MAP_CATEGORY = (from map_category in PRO_DOCSDatabaseDataContext.MapCategories
                                                 where map_category.MapCategoryID.Equals(CURRENT_SELECTED_MAP_CATEGORY.MapCategoryID)
                                                 select map_category).FirstOrDefault();

                txtCategoryName.Text = CURRENT_SELECTED_MAP_CATEGORY.MapCategoryName;
                comboDepartmentStorageMedia.Text = CURRENT_SELECTED_MAP_CATEGORY.ARCHIVE_DEPARTMENTS_STORAGES_HEIRARCHy.ARCHIVE_DEPARTMENT_STORAGE_HEIRARCHY_NAME;
                chkIsActive.Checked = !CURRENT_SELECTED_MAP_CATEGORY.IsDeleted.Value;
                string file_image_path = string.Empty;

                this.picCategoryIcon.Image = Image.FromFile(@"Resources\country_32x32.png");

                if (!string.IsNullOrEmpty(CURRENT_SELECTED_MAP_CATEGORY.MapCategoryIcon))
                {
                    List<string> file_pathes = (from pathes in PRO_DOCSDatabaseDataContext.ARCHIVE_DEPARTMENTS_STORAGES_HEIRARCHY_PHYSICAL_PATHEs
                                                where pathes.ARCHIVE_DEPARTMENT_STORAGE_HEIRARCHY_ID.Value.Equals(CURRENT_SELECTED_MAP_CATEGORY.ARCHIVE_DEPARTMENT_STORAGE_HEIRARCHY_ID.Value)
                                                select pathes.ARCHIVE_DEPARTMENTS_STORAGES_HEIRARCHY_PHYSICAL_PATH).ToList();

                    for (int i = 0; i < file_pathes.Count; i++)
                    {
                        FileInfo fiImage = new FileInfo(Path.Combine(file_pathes[i], CURRENT_SELECTED_MAP_CATEGORY.MapCategoryIcon));

                        if (fiImage.Exists)
                        {
                            this.picCategoryIcon.Image = Image.FromFile(fiImage.FullName);
                            break;
                        }
                    }
                }
                else
                {
                }

            }

        }
    }
}
